package com.shizhanzhe.qdd.home.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.qdd.BuildConfig;
import com.shizhanzhe.qdd.R;
import com.shizhanzhe.qdd.base.UserBean;
import com.shizhanzhe.qdd.home.dialog.PhotoDialog;
import com.shizhanzhe.qdd.url.Path;
import com.shizhanzhe.qdd.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.qdd.utils.SharedPreferencesUtils;
import com.shizhanzhe.qdd.utils.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyInfoActivity extends AppCompatActivity {

    @BindView(R.id.top_back)
    ImageButton topBack;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.iv_person_headImg)
    ImageView ivPersonHeadImg;
    @BindView(R.id.ll_person_headImg)
    LinearLayout llPersonHeadImg;
    @BindView(R.id.et_person_username)
    EditText etPersonUsername;
    @BindView(R.id.tv_person_commit)
    TextView tvPersonCommit;
    @BindView(R.id.ll_person_root)
    LinearLayout llPersonRoot;
    private PhotoDialog mPhotoDialog;
    public static final int IMAGE_REQUEST_CODE = 0;
    public static final int CAMERA_REQUEST_CODE = 1;
    public static final int RESIZE_REQUEST_CODE = 2;
    private String IMAGE_FILE_NAME = "header.jpg";
    private File file;   //裁剪前
    private String mFile = ""; //裁剪后图片地址
    private Uri uri;
    private String changeimg = "";//上传到服务器返回图片路径
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true, 0.2f)
                .init();
        TextView title = findViewById(R.id.top_title);
        title.setText("个人资料");
        etPersonUsername.setText(UserBean.nickname);
        Glide.with(MyInfoActivity.this).load(UserBean.headimg)
                .into(ivPersonHeadImg);
        setListener();
    }

    private void setListener() {
        findViewById(R.id.top_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //修改头像
        findViewById(R.id.ll_person_headImg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPhotoDialog = new PhotoDialog(MyInfoActivity.this);
                mPhotoDialog.setPhotoListener(new PhotoDialog.PhotoListener() {
                    @Override
                    public void chooseCamera() {
                        mPhotoDialog.dismiss();
                        //相机
                        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                                + "/icandy/" + IMAGE_FILE_NAME);
                        file.getParentFile().mkdirs();
                        //改变Uri
                        uri = FileProvider.getUriForFile(MyInfoActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", file);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            int checkCallPhonePermission = ContextCompat.checkSelfPermission(MyInfoActivity.this, Manifest.permission.CAMERA);
                            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(MyInfoActivity.this, new String[]{android.Manifest.permission.CAMERA}, 3);
                                return;
                            } else {
                                Intent cameraIntent = new Intent(
                                        "android.media.action.IMAGE_CAPTURE");
                                //添加权限
                                cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                                startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                            }
                        } else {
                            int checkCallPhonePermission = ContextCompat.checkSelfPermission(MyInfoActivity.this, Manifest.permission.CAMERA);
                            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(MyInfoActivity.this, new String[]{android.Manifest.permission.CAMERA}, 1);
                                return;
                            } else {
                                Intent cameraIntent = new Intent(
                                        "android.media.action.IMAGE_CAPTURE");
                                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                                cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                                startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                            }
                        }
                    }

                    @Override
                    public void choosePhoto() {
                        mPhotoDialog.dismiss();
                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, IMAGE_REQUEST_CODE);
                    }

                    @Override
                    public void chooseClose() {
                        mPhotoDialog.dismiss();
                    }
                });
                mPhotoDialog.show();
                Display d = getWindowManager().getDefaultDisplay();
                WindowManager.LayoutParams p = mPhotoDialog.getWindow().getAttributes();
                p.width = d.getWidth();
                mPhotoDialog.getWindow().setAttributes(p);
            }
        });
        //提交
        findViewById(R.id.tv_person_commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { saveMsg(2);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case IMAGE_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    resizeImage(data.getData());
                }
                break;
            case CAMERA_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        resizeImage(uri);
                    } else {
                        resizeImage(Uri.fromFile(file));
                    }
                }
                break;
            case RESIZE_REQUEST_CODE:
                Bitmap photo = BitmapFactory.decodeFile(mFile);
                Util.saveBitmap(this, photo, mFile);
                postSaveImg(mFile);
                //ivPersonHeadImg.setImageBitmap(photo);
                break;
            default:
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 3:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //这里已经获取到了摄像头的权限，想干嘛干嘛了可以
                    Intent cameraIntent = new Intent(
                            "android.media.action.IMAGE_CAPTURE");
                    //添加权限
                    cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                } else {
                    //这里是拒绝给APP摄像头权限，给个提示什么的说明一下都可以。
                    Toast.makeText(MyInfoActivity.this, "请手动打开相机权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void resizeImage(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        File out = new File(getPath());
        if (!out.getParentFile().exists()) {
            out.getParentFile().mkdirs();
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
        startActivityForResult(intent, RESIZE_REQUEST_CODE);
    }

    //裁剪后的地址
    private String getPath() {
        //resize image to thumb
        if ("".equals(mFile)) {
            mFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test/outtemp.png";
        }
        return mFile;
    }

    //头像上传接口
    private void postSaveImg(String imagePath) {
        File f = new File(imagePath);
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), f);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("avatar", f.getName(), fileBody)
                .build();
        Request request = new Request.Builder()
                .url(Path.avatarUpload)
                .post(requestBody)
                .build();
        final Handler handler = new Handler();
        final Call call = new OkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (e.toString().contains("SocketTimeoutException")) {//网络超时
                            Log.d("error", "1");
                        } else if (e.toString().contains("UnknownHostException")) {//网络异常
                            Log.d("error", "2");
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String str = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        changeimg = str;
                        Log.d("______", changeimg);
                        saveMsg(1);
                    }
                });
            }
        });
    }

    //保存头像接口  1修改头像
    private void saveMsg(int types) {
        type = types;
        String url = "";
        if (type == 1) {
            url = Path.personal_xiu + "?uid=" + UserBean.uid + "&avatar=" + changeimg + "&uname=" + etPersonUsername.getText().toString();
        } else if (type == 2) {
            url = Path.personal_xiu + "?uid=" + UserBean.uid + "&avatar=" + UserBean.headimg + "&uname=" + etPersonUsername.getText().toString();
        }
        OkHttpDownloadJsonUtil.downloadJson(this, url,
                new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        if (!"1".equals(json) && !"2".equals(json)) {
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                                if (jsonObject.has("info")) {
                                    Toast.makeText(MyInfoActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                                }
                                if (jsonObject.has("status")) {
                                    if (jsonObject.getInt("status") == 1) {
                                        if (type == 1) {
                                            UserBean.headimg = changeimg;
                                            SharedPreferencesUtils.setParam(MyInfoActivity.this, "headimg", UserBean.headimg);
                                            Log.d("headimg", changeimg + "!!!!!!" + Path.BASE_URL + UserBean.headimg);
                                            //ivPersonHeadImg.setImageBitmap(photo);
                                            Glide.with(MyInfoActivity.this).load(UserBean.headimg)
                                                    .into(ivPersonHeadImg);
                                        } else if (type == 2) {
                                            UserBean.nickname = etPersonUsername.getText().toString();
                                            SharedPreferencesUtils.setParam(MyInfoActivity.this, "nickname", UserBean.nickname);
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
}
